import axios from 'axios';
import { showFailToast } from 'vant';
// import qs from 'qs';
import envConfig from '@/config';

const baseURL = envConfig[`VUE_APP_${envConfig.env.toUpperCase()}_BASE_URL`];

const instance = axios.create({
  baseURL,
  timeout: 30000,
  // paramsSerializer(params) {
  //   // 'indices' | 'brackets' | 'repeat' | 'comma' |
  //   return qs.stringify(params, { arrayFormat: 'repeat', encode: false });
  // },
  // transformRequest: [
  //   (data, data2) => {
  //     console.log(data, data2);
  //     return data;
  //   },
  // ],
});

if (envConfig.env === 'development') {
  instance.interceptors.request.use((request) => request);
  instance.interceptors.response.use((response) => {
    /* eslint-disable no-console */
    console.log(`请求${response.config.url.replace(new RegExp(response.config.baseURL), '')}返回的Mock数据:`);
    console.dir(response.data);
    return response;
  });
}

// 拦截器
instance.interceptors.request.use(
  async (request) => {
    request.params = request.params || {};
    request.data = request.data || {};
    request.withCredentials = true;
    request.headers['Authorization'] = 'YyPhuktDZtOnnaWlOepyBheBWRzWQI3';

    if (!request.headers['lang']) {
      request.headers['lang'] = 'zh-CN';
    }
    request.headers['version'] = envConfig.version;

    console.log(request);
    return request;
  },
  (error) => Promise.reject(error)
);

instance.interceptors.response.use(
  (response) => {
    // 阻止options
    if (response.status === 200 && response.config.method.toLowerCase() === 'options') return false;
    const { to } = response.config;
    const meta = (to || {}).meta || {};

    if (response.status !== 200) {
      return Promise.reject(response);
    }
    // 处理格式异常
    /* eslint-disable no-param-reassign */
    if (response.data.data === '{}') {
      response.data.data = JSON.parse(response.data.data);
    }

    /* eslint-enable */
    // 当前商品需登录才能查看 (-8)
    if ([-8].some((code) => code === response.data.code)) {
      localStorage.removeItem('token');
      // 无需登录
      if (meta.auth === 0) {
        return Promise.resolve(response.data);
      }
      // 缺少access_token参数
      if (response.data.code === 41001) {
        showFailToast(instance.i18n.global.t('cfmoto.api.http.401'));
      }
      // 未登录
      // if (response.data.code === 41002) {
      //   showFailToast('登录失效，请重新登录！');
      // }
      // 重新登录
      if (response.data.code === 41002) {
        showFailToast(instance.i18n.global.t('cfmoto.api.http.401'));
      }
      // 未知的登录用户
      if (response.data.code === 10022) {
        showFailToast(instance.i18n.global.t('cfmoto.api.http.401'));
      }
    } else {
      return Promise.resolve(response.data);
    }

    return Promise.reject(response.data);
  },
  (error) => {
    console.log('=========   error');
    console.log(error);
    return Promise.reject(error);
  }
);

instance.useRouter = function useRouter(router) {
  instance.router = router;
  return instance;
};

instance.useStore = function useStore(store) {
  instance.store = store;
  return instance;
};

instance.useI18n = function useI18n(i18n) {
  instance.i18n = i18n;
  return instance;
};

export default instance;
